﻿using System;
using System.Collections.Generic;
using System.IO;
using Nutilities.Net;

namespace Auktionshuset___Server
{
    public class Auction : IBinaryWriteable, IBinaryUpdateable
    {
        private static int _nextId = 1;

        // Client / Server shared
        public int Id { get; set; }

        public string Title { get; set; }
        public string Description { get; set; }
        public User Owner { get; set; }

        public byte[] ImageBytes { get; set; }

        public decimal CurrentBid { get; set; }
        public decimal NextBid { get; set; }

        public DateTime Starts { get; set; }
        public DateTime Ends { get; set; }

        public bool Active { get; set; }

        public User HighestBidder { get; set; }

        public string StatusMessage { get; set; }

        // Server specific
        public List<Client> Subscribers { get; set; }

        public AuctionThread Thread { get; set; }

        public Auction()
        {
            Id = _nextId++;

            Subscribers = new List<Client>();
            StatusMessage = "";
        }

        public void WriteTo(BinaryWriter writer)
        {
            writer.Write(Id);

            writer.Write(Title);
            writer.Write(Description);
            writer.Write(Owner.Alias);

            writer.Write(ImageBytes.Length);
            writer.Write(ImageBytes);

            writer.Write(CurrentBid);
            writer.Write(NextBid);

            writer.Write(Starts.ToBinary());
            writer.Write(Ends.ToBinary());

            writer.Write(Active);

            writer.Write(HighestBidder != null);
            if (HighestBidder != null)
                HighestBidder.WriteTo(writer);

            writer.Write(StatusMessage);
        }

        public void UpdateTo(BinaryWriter writer)
        {
            // Header
            writer.Write(Id);

            writer.Write(CurrentBid);
            writer.Write(NextBid);

            writer.Write(Active);

            writer.Write(HighestBidder != null);
            if (HighestBidder != null)
                HighestBidder.WriteTo(writer);

            writer.Write(StatusMessage);
        }
    }
}